package org.liujing.jsw.client.ui;

import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.*;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.*;
import org.liujing.jsw.client.ui.plaf.*;
import org.liujing.jsw.client.bundle.*;
import java.util.logging.*;

@SuppressWarnings("deprecation")
public class ImageIcon extends PlainComponent{
	static Logger log = Logger.getLogger("client.ImageIcon");
	private Element imgEl;
	
	public ImageIcon(String path){
		Element divEl = DOM.createDiv();	
		imgEl = DOM.createImg();
		divEl.appendChild(imgEl);
		setDomElement(divEl);
		//setDomElement(el);
		DOM.sinkEvents(imgEl, Event.ONLOAD);
		imgEl.setPropertyString("src", path);
	}
	
	public ImageIcon(BundledImage image){
		Element divEl = DOM.createDiv();
		setDomElement(divEl);
		log.fine("apply");
		image.applyTo(divEl);
		setPreferredSize(new Dimension(image.width, image.height));
		setMaximumSize(new Dimension(image.width, image.height));
		setMinimumSize(new Dimension(image.width, image.height));
	}
	
	
	
	protected void resizeImage(){
		
		int w = imgEl.getScrollWidth();
		int h = imgEl.getScrollHeight();
		//Window.alert("set");
		if(!isPreferredSizeSet()){
			setPreferredSize(new Dimension(w, h));
			GWT.log("img loaded size: "+ w +", " + h);
			
		}
		if(!isMaximumSizeSet())
			setMaximumSize(new Dimension(w, h));
		revalidate();
	}
	
	public static class UIFactory implements ComponentUIFactory{
		ImageIconUI ui = new ImageIconUI();
		
		public ComponentUI createUI(){
			return ui;
		}
	}
	
	public static class ImageIconUI extends ComponentUI{
		
		public void installUI(JComponent c) {
			((ImageIcon)c).addDomHandler(new ImgLoadHandler((ImageIcon)c), LoadEvent.getType());
		}
		
		public Dimension getPreferredSize(JComponent c) {
			ImageIcon icon = (ImageIcon)c;
			int w = 15, h = 10;
			if(icon.imgEl != null){
				w = icon.imgEl.getScrollWidth();
				h = icon.imgEl.getScrollHeight();
			}
			return new Dimension(w, h);
		}
	}
	
	static class ImgLoadHandler implements LoadHandler{
		ImageIcon icon;
		public ImgLoadHandler(ImageIcon target){
			icon = target;
		}
		
		public void onLoad(LoadEvent event){			
			
			icon.resizeImage();
		}
	}
}
